<template>
  <div class="contain">
    <div class="topKey">
      <div class="top">
        <el-date-picker
          v-model="topKeyDate"
          type="daterange"
          range-separator="-"
          start-placeholder="Start date"
          end-placeholder="End date"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disableFutureDates"
        />
        <el-select
          v-model="chartTopKeyType"
          placeholder="请选择图表类型"
          style="width: 200px; margin-left: 20px"
        >
          <el-option label="柱状图" value="bar"></el-option>
          <el-option label="饼图" value="pie"></el-option>
        </el-select>
      </div>
      <div ref="topKeyCharts" class="topKeyCharts"></div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { onMounted, ref, watch } from 'vue'
import { getDailyKeyStats } from '@/api/statistics'
import { ElMessage } from 'element-plus'

const topKeyDate = ref([
  dayjs().format('YYYY-MM-DD'), // 默认选中当天
  dayjs().format('YYYY-MM-DD'),
])
const topKeyCharts = ref(null)
const chartTopKeyType = ref('bar')
const topKetData = ref([])

const disableFutureDates = (date) => {
  return date.getTime() > new Date().getTime() // 禁止选择今天之后的日期
}
watch(topKeyDate, () => {
  if (topKeyDate.value.length === 2) {
    const startDate = dayjs(topKeyDate.value[0])
    const endDate = dayjs(topKeyDate.value[1])
    const diffDays = endDate.diff(startDate, 'day')
    if (diffDays > 7) {
      ElMessage.warning('时间范围不能超过 7 天，请重新选择！')
      topKetData.value = []
      topKeyDate.value = []
      return
    }
  }
  getTopKeyData()
})
watch(chartTopKeyType, () => {
  renderKeyChart()
})
const renderKeyChart = () => {
  const dates = topKetData.value.map((item) => item.date)
  const values = topKetData.value.map((item) => item.keyCount)
  const option =
    chartTopKeyType.value === 'bar'
      ? {
          title: {
            text: '用户搜索次数',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: dates,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '搜索次数',
              type: 'bar',
              data: values,
              barWidth: 40, // 设置柱子的固定宽度（可以调整）
              label: {
                show: true, // 显示标签
                position: 'top', // 标签位置
                formatter: '{c}次', // 在柱子上显示百分数
              },
            },
          ],
        }
      : {
          title: {
            text: '用户搜索次数',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
          },
          series: [
            {
              name: '搜索次数',
              type: 'pie',
              radius: '50%',
              data: topKetData.value.map((item) => ({
                name: item.date,
                value: item.keyCount,
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        }
  const chart = echarts.init(topKeyCharts.value)
  chart.setOption(option, true)
}
onMounted(() => {
  getTopKeyData()
})
const getTopKeyData = async () => {
  const res = await getDailyKeyStats({
    startDate: topKeyDate.value[0],
    endDate: topKeyDate.value[1],
  })
  if (res.status === 200 || res.status === 201) {
    topKetData.value = res.data.data
    renderKeyChart()
  }
}
</script>

<style lang="scss" scoped>
.contain {
  padding: 30px;
  .topKeyCharts {
    margin-top: 20px;
    width: 1000px;
    height: 400px;
  }
}
</style>
